﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MS.InformationManagement.Support;
using MS.InformationManagement.DAL.DocumentCenter;
using Microsoft.SharePoint;
using MS.InformationManagement.DAL.DTOs;

namespace MS.InformationManagement.Core.Support
{
    public static class BusinessDateHelper
    {

        public static DateTime GetNextBusinessDay(DateTime currentDate)
        { 
            DateTime nextBusinessDay = currentDate;
            do
            {
                nextBusinessDay = nextBusinessDay.AddDays(1);
            } while (!IsBusinessValidDay(nextBusinessDay));
            return nextBusinessDay;
        }

        public static bool IsBusinessValidDay(DateTime currentDate)
        {
            if (!DateTimeHelper.IsWeekDay(currentDate))
                return false;
            if(IsHoliday(currentDate))
                return false;
            return true;
        }

        private static bool IsHoliday(DateTime currentDate)
        {
            using (var dc = new DCDocumentCenterDataContext(SPContext.Current.Web.Url))
            {
                var day = (from holiday in dc.DiasFestivos
                           where holiday.Fecha == currentDate
                           select holiday).FirstOrDefault();
                return day != null;
            }
        }

        public static IEnumerable<FestivoDTO> GetHolidays(DateTime startDate, DateTime endDate)
        {
            IEnumerable<FestivoDTO> foundElements = null;
            using (DCDocumentCenterDataContext ctx = new DCDocumentCenterDataContext(SPContext.Current.Web.Url)) {
                foundElements = (from holiday in ctx.DiasFestivos
                                 where holiday.Fecha >= startDate && holiday.Fecha <= endDate
                                 select new FestivoDTO { Title = holiday.Title, DateTime = holiday.Fecha });
            }
            return foundElements;
        }


    }
}
